#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@author: yuejl
@application:
@contact: lewyuejian@163.com
@file: httpclient.py
@time: 2021/8/15 0015 0:37
@desc:
'''
import requests
import re
import allure
from loguru import logger
from typing import Dict
from common.parser import build_url
from common.models import HttpResponseResult
absolute_http_url_regexp = re.compile(r"^https?://", re.I)

class HttpClient(requests.Session):
    def __init__(self, url=None):
        super(HttpClient, self).__init__()
        self._url = url
        self._encoding = 'utf-8'
        self._session = requests.Session()
        self._headers = {}
        #self.variables = {}

    default_header = {
        "Content-Type": "application/json"
    }

    def setHeaders(self, headers):
        self._headers = headers

    def updateHeaders(self, headers):
        # 判断迭代对象是否为空
        if headers:
            self._headers.update(headers)

    def getHeaders(self):
        return self._headers

    def send_request_mode(self, url, method, **kwargs):
        #kwargs.setdefault(headers.update(self.default_header))
        r = self._session.request(method, url, **kwargs)
        return r

    def send_request_v2(self, variables: Dict, is_json=True):
        # 判断url的值为空
        if variables.get('url'):
            url = build_url(self._url, variables.get('url'))
        else:
            url = self._url
        headers = self.updateHeaders(variables.get('headers'))
        method = variables.get('method')
        body = variables.get('json')
        print(variables.get('json'))
        print(type(variables.get('json')))
        self.create_request_log(url, method, body, headers)
        if method in ['GET', 'get']:
            resp = self.send_request_mode(url, 'GET', params=body)
        elif method in ['POST', 'post']:
            if is_json:
                resp = self.send_request_mode(url, 'post', json=body, headers=headers)
            else:
                resp = self.send_request_mode(url, 'post', data=body, headers=headers)
        self.create_response_log(resp.status_code, resp.text)
        return resp


    def _dealResponseResult(self,r):
        """
        将请求结果封装到HttpResponseResult
        :param r: requests请求响应
        :return:
        """
        r.encoding=self._encoding
        httpResponseResult = HttpResponseResult()
        #httpResponseResult.status_code=r.status_code
        httpResponseResult.headers=r.headers.__str__()
        #httpResponseResult.cookies=r.cookies.__str__()
        httpResponseResult.body=r.content.decode(self._encoding)
        return httpResponseResult

    def closeSession(self):
        self._session.close()

    @allure.step("请求日志")
    def create_request_log(self, url, method, body, header):
        pass

    @allure.step('响应日志')
    def create_response_log(self, status_code, text):
        pass
